# _*_ coding: UTF-8 _*_
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from APKManager.helper import Helper, get_request_parameters, model_find, model_set
from Common.base_exception import GBErr
from webconf import *
from templatetags.filter import download_url
from menu import Menu
import logging
from django.http import *
#
# LOGIN_URL = "/APKManager/login/"
# LOGOUT_URL = "/APKManager/logout/"
#
#
# def config_render(method):
#     def wraped(request, *args, **kwargs):
#         privs = int(request.session.get('privileges', 0))
#         render_args = {
#             'status_model': status_model,
#             'bank_mode': bank_model,
#             'GameStyle': GameStyle,
#             'GameType': GameType,
#             'GameCategory': GameCategory,
#             'GameOperationMode': GameOperationMode,
#             'GamePayMode': GamePayMode,
#             'GameReleaseMode': GameReleaseMode,
#             'urls': {
#               'logout': LOGOUT_URL,
#               'update': '/APKManager/update_password',
#             },
#             'user': request.session.user,
#         }
#
#         menu_list = get_menu_by_privileges(privs)
#         item = request.session.get('item', 0)
#         subitem = request.session.get('subitem', 0)
#
#         menu_list[item]['active'] = True
#         if menu_list[item]["sub_menus"]:
#             menu_list[item]["sub_menus"][subitem]["active"] = True
#
#         render_args["menu_list"] = menu_list
#         kwargs['render_args'] = render_args
#         return method(request, *args, **kwargs)
#
#     return wraped
#
#
# class FileForm(forms.Form):
#     file = forms.FileField()
#
#
# class Utils(object):
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     def update_password(request, *args, **kwargs):
#         new_pwd = request.POST.get('new_password')
#         old_pwd = request.POST.get('old_password')
#         user = request.session.user
#         try:
#             if hashlib.md5(old_pwd).hexdigest() != user.password:
#                 return json_response(APKError.InvalidPassword)
#
#             user.password = hashlib.md5(new_pwd).hexdigest()
#
#             user.save(force_update=True)
#             return json_response(APKError.Ok)
#         except:
#             return json_response(APKError.Exception)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     def upload_file(request, *args, **kwargs):
#         def _save_file(path, f):
#             with open(path, "wb+") as fp:
#                 for chunk in f.chunks():
#                     fp.write(chunk)
#
#         user = request.session.user
#         udir = "%s/%s" % (ApkmanagerConfig.upload_to, user.account)
#         # if the user directory does not exist.
#         if not os.path.exists(udir):
#             try:
#                 os.mkdir(udir)
#             except:
#                 return HttpResponseServerError()
#
#         for f in request.FILES.getlist('file'):
#             path = "%s/%s" % (udir, f.name)
#             try:
#                 _save_file(path, f)
#             except Exception as e:
#                 logging.error("can not save file due to %s." % (str(e)))
#                 return HttpResponseServerError()
#
#         return HttpResponse()
#
#     @staticmethod
#     @login_required(login_url=LOGOUT_URL)
#     def download_file(request, *args, **kwargs):
#         user = request.session.user
#         try:
#             if request.method == "POST":
#                 filename = request.POST.get('file')
#             else:
#                 filename = request.GET.get('file')
#         except:
#             return HttpResponseBadRequest()
#
#         try:
#             path = "%s/%s/%s" % (ApkmanagerConfig.upload_to, user.account, filename)
#             if not os.path.exists(path):
#                 return HttpResponseNotFound()
#
#             with open(path, "rb") as fp:
#                 content = fp.read()
#                 resp = HttpResponse(content, content_type='application/octet-stream')
#                 md5 = hashlib.md5()
#                 md5.update(content)
#                 resp["Content-MD5"] = md5.hexdigest()
#                 resp["Content-Disposition"] = 'inline;filename=' + os.path.basename(filename)
#                 return resp
#         except:
#             return HttpResponseServerError()
#
#
# class personal_center(object):
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadCPInfo, error_url=LOGIN_URL)
#     @config_render
#     def edit(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#         cpinfo = model_find(WbCpInfo, account=request.session.user)
#         render_args['cp'] = cpinfo
#         render_args['urls']["submit"] = "/APKManager/personal_center/submit.pp"
#
#         if not cpinfo:
#             return render(request, 'html/upload_supplier.html', render_args)
#         if cpinfo.status == Status.kSubmitted or cpinfo.status == Status.kInAuditing:
#             return render(request, 'html/supplier_submitted.html', render_args)
#         elif cpinfo.status == Status.kRejected:
#             return render(request, 'html/upload_supplier.html', render_args)
#         elif cpinfo.status == Status.kAccepted:
#             return render(request, 'html/show_supplier.html', render_args)
#         return HttpResponseBadRequest()
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadCPInfo, error_url=LOGIN_URL)
#     @config_render
#     def submit(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#         try:
#             if not WbCpInfo.submit(request):
#                 raise APKError.Exception
#
#             return render(request, 'html/supplier_submitted.html', render_args)
#         except GBErr as e:
#             return HttpResponse(e.errmsg)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadCPInfo | Priv.kFirstTrial | Priv.kUploadGame,
#                         error_url=LOGIN_URL)
#     @config_render
#     def query(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#
#         if request.method == "GET":
#             cid = request.GET.get('id')
#             if not cid:
#                 return HttpResponseBadRequest()
#
#             render_args["cp"] = model_find(WbCpInfo, id=int(cid))
#             return render(request, 'html/show_supplier.html', render_args)
#
#
# class game_center(object):
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadGame, error_url=LOGIN_URL)
#     @config_render
#     @cpinfo_required(error_message="请提交资质，如果已经提交请耐心等待审核……谢谢！")
#     def edit(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#
#         render_args['urls']["save"] = "/APKManager/game_center/save.pp"
#         render_args['urls']['submit'] = "/APKManager/game_center/commit.pp"
#
#         if request.method == "GET":
#             id = request.GET.get('id')
#             if id:
#                 game = model_find(WbGame, id=int(id))
#                 render_args['game'] = game
#
#             return render(request, 'html/t_upload_game.html', render_args)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadGame, error_url=LOGIN_URL)
#     @config_render
#     def delete(request, *args, **kwargs):
#         if request.method == "GET":
#             id = request.GET.get('id')
#             if not id:
#                 return HttpResponseBadRequest()
#
#             game = model_find(WbGame, id=int(id))
#             if not game or game.status == Status.kInAuditing:
#                 return HttpResponseBadRequest()
#
#             game.delete()
#             return HttpResponseRedirect("/APKManager/game_center/query.pp?type=2&status=255")
#             pass
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadGame, error_url=LOGIN_URL)
#     @config_render
#     def save(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#         try:
#             WbGame.save_game(request, commit=False)
#             return render(request, 'html/t_game_submitted.html', render_args)
#         except GBErr as e:
#             return HttpResponse(e.errmsg)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @config_render
#     def commit(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#         try:
#             WbGame.save_game(request, commit=True)
#             return render(request, 'html/t_game_submitted.html', render_args)
#         except GBErr as e:
#             return HttpResponse(e.errmsg)
#         except Exception as e:
#             return HttpResponse(str(e))
#
#         # try:
#         #     if request.method == "POST":
#         #         form = GameForm(request.POST, request.FILES)
#         #         if not form.is_valid():
#         #             print(str(form.errors))
#         #             return HttpResponseBadRequest()
#         #         form.commit(request.session.user, committed=True)
#         #         return render(request, 'html/t_game_submitted.html', render_args)
#         # except GBErr as e:
#         #     return HttpResponseBadRequest(e.errmsg)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kUploadGame, error_url=LOGIN_URL)
#     @config_render
#     def query(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#
#         render_args['urls']['query'] = '/APKManager/game_center/query.pp'
#         render_args['urls']['edit'] = '/APKManager/game_center/edit.pp'
#         render_args['urls']['delete'] = '/APKManager/game_center/delete.pp'
#
#         if request.method == "GET":
#             gid = request.GET.get('id')
#             if gid:
#                 game = model_find(WbGame, id=int(gid))
#                 render_args['game'] = game
#                 return render(request, 'html/t_show_game.html', render_args)
#             else:
#                 status = request.GET.get('status', Status.kAccepted)
#                 if int(status) != Status.kAccepted:
#                     type = request.GET.get('type', 0)
#                     render_args["type"] = int(type)
#                 render_args["status"] = int(status)
#                 return render(request, 'html/t_query_game_list.html', render_args)
#         elif request.method == "POST":
#             status = int(request.POST['status'])
#             offset = int(request.POST.get('iDisplayStart'))
#             max_num = int(request.POST.get('iDisplayLength'))
#             orderby = None
#
#             total = WbGame.get_total(status=status)
#             game_list = WbGame.query(max_num, offset, orderby, False, status=status)
#
#             resp_data = {
#                 'sEcho': request.POST.get('sEcho'),
#                 'iTotalRecords': 0,
#                 'iTotalDisplayRecords': total,
#                 'aaData': []
#             }
#
#             for game in game_list:
#                 index = 0
#                 json_data = {
#                     'index': offset + index,
#                     'name': game.descriptor.name,
#                     'version': game.version_no,
#                     'category': Choice.getChoice(GameCategory.Categories, game.descriptor.category),
#                     'type': Choice.getChoice(GameType.Types, game.descriptor.type),
#                     'paymode': Choice.getChoice(GamePayMode.PayModes, game.descriptor.paymode),
#                     'id': game.id,
#                     'status': status,
#                     'ctime': game.ctime,
#                     'mtime': game.mtime,
#                     'stime': game.stime,
#                     'atime': game.atime,
#                 }
#                 try:
#                     audit_record = WbGameAudit.query_records(game)[-1]
#                     json_data["last_auditor"] = audit_record.auditor.account
#                 except:
#                     pass
#                 index += 1
#                 resp_data['aaData'].append(json_data)
#             return JsonResponse(resp_data)
#
#
# class auditing_center(object):
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kVerifyCP)
#     @config_render
#     def query_cp(request, *args, **kwargs):
#         if request.method == "POST":
#             orderby = None
#             offset = int(request.POST.get('iDisplayStart'))
#             max_num = int(request.POST.get('iDisplayLength'))
#             status = int(request.POST.get('status', Status.kInAuditing))
#             total = WbCpInfo.get_total(status=status)
#
#             resp_data = {
#                 'sEcho': request.POST.get('sEcho'),
#                 'iTotalRecords': max_num,
#                 'iTotalDisplayRecords': total,
#                 'aaData': []
#             }
#             for p in WbCpInfo.query(max_num, offset, orderby, False, status=status):
#                 resp_data['aaData'].append({'index': 0,
#                                             'company': p.company,
#                                             'name': p.account.account,
#                                             'id': p.id,
#                                             'ctime': p.ctime})
#             return JsonResponse(resp_data)
#         elif request.method == "GET":
#             render_args = kwargs.get('render_args')
#             render_args['urls']['query'] = '/APKManager/auditing_center/query_cp.pp'
#             render_args['urls']['check_cp_info'] = "/APKManager/personal_center/query.pp"
#             render_args['urls']['confirm'] = '/APKManager/auditing_center/audit_cp.pp'
#             return render(request, 'html/t_audit_aptitude.html', render_args)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kVerifyCP)
#     def audit_cp(request, *args, **kwargs):
#         if request.method == "POST":
#             try:
#                 flag = int(request.POST['flag'])
#                 id = int(request.POST['id'])
#                 desc = request.POST.get('description')
#                 cpinfo = model_find(WbCpInfo, id=id)
#
#                 if not cpinfo:
#                     raise APKError.NoCPFound
#                 cpinfo.confirm(not flag, desc)
#                 return json_response(APKError.Ok)
#             except GBErr as e:
#                 return json_response(e)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kFirstTrial | Priv.kReview)
#     @config_render
#     def check_game_info(request, *args, **kwargs):
#         render_args = kwargs.get('render_args')
#
#         if request.method == "GET":
#             id = request.GET.get('id')
#             game1 = model_find(WbGame, id=int(id))
#             render_args['game1'] = game1
#
#             if game1.descriptor.pointer > 0:
#                 game2 = model_find(WbGame, id=game1.descriptor.pointer)
#                 render_args['game2'] = game2
#
#             return render(request, 'html/t_show_game_auditing_log.html', render_args)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kFirstTrial | Priv.kReview)
#     @config_render
#     def audit_game(request, *args, **kwargs):
#         try:
#             id = int(request.POST.get('id'))
#             status = int(request.POST.get('flag'))
#             level = int(request.POST.get('level'))
#             desc = request.POST.get('description')
#             report = request.FILES.get('report{0}'.format(id))
#
#             game = model_find(WbGame, id=int(id))
#             if not game:
#                 return HttpResponseBadRequest()
#
#             priv = Priv.get_privilege(request.session.user)
#             if bool(status):
#                 status = Status.kAccepted
#             else:
#                 status = Status.kRejected
#
#             if (priv & Priv.kFirstTrial) and level == 1:
#                 result, status = WbGameAudit.confirm(game, request.session.user, int(status), desc,
#                                                      report)
#
#             if (priv & Priv.kReview) and level == 2:
#                 result, status = WbGameAudit.confirm(game, request.session.user, int(status), desc,
#                                                      report)
#
#             return json_response(APKError.Ok)
#         except GBErr as e:
#             return json_response(e)
#         except Exception as e:
#             return json_response(APKError.Exception)
#
#     @staticmethod
#     @login_required(login_url=LOGIN_URL)
#     @privilege_required(privilege=Priv.kFirstTrial | Priv.kReview)
#     @config_render
#     def query_game(request, *args, **kwargs):
#         if request.method == "POST":
#             offset = int(request.POST.get('iDisplayStart'))
#             max_num = int(request.POST.get('iDisplayLength'))
#             status = int(request.POST.get('status'))
#             level = int(request.POST.get('level'))
#             orderby = None
#             sort = False
#
#             resp_data = {
#                 'sEcho': request.POST.get('sEcho'),
#                 'iTotalRecords': max_num,
#                 'iTotalDisplayRecords': 0,
#                 'aaData': []
#             }
#             try:
#                 games = WbGameAudit.query_audit_records(level, status)
#             except:
#                 games = []
#
#             resp_data["iTotalDisplayRecords"] = len(games)
#             resp_data["iTotalRecords"] = len(games)
#
#             for g in games:
#                 ginfo = {"index": 0,
#                          "name": g.game.descriptor.name,
#                          "id": g.game.id,
#                          "type": Choice.getChoice(GameType.Types, g.game.descriptor.type),
#                          "stime": g.game.stime,
#                          "description": g.description,
#                          "report": download_url(g.audit_report.name)}
#                 resp_data['aaData'].append(ginfo)
#
#             return JsonResponse(resp_data)
#         elif request.method == "GET":
#             def get_title(level, status):
#                 title_map = [
#                     ["初审打回列表", "", "", "初审待审核列表", "初审通过列表"],
#                     ["复审打回列表", "", "", "复审待审核列表", "复审通过列表"]
#                 ]
#
#                 try:
#                     return title_map[level - 1][status + 1]
#                 except:
#                     return "Unknown"
#
#             render_args = kwargs.get('render_args')
#             render_args['urls']['query'] = '/APKManager/auditing_center/query_game.pp'
#             render_args['urls']['check_game_info'] = '/APKManager/auditing_center/check_game_info.pp'
#             render_args['urls']['confirm'] = '/APKManager/auditing_center/audit_game.pp'
#
#             try:
#                 status = int(request.GET.get('status'))
#                 level = int(request.GET.get('level'))
#                 render_args['status'] = status
#                 render_args['level'] = level
#                 render_args['title'] = get_title(level, status)
#                 return render(request, 'html/t_audit_firstTrial.html', render_args)
#             except:
#                 return HttpResponseBadRequest()
#
#
# def get_menu_by_privileges(priv):
#     menu_list = []
#     personal = Menu("个人中心", '', "/APKManager/personal_center/edit.pp")
#     if priv & Priv.kUploadCPInfo:
#         personal.add_sub_menu(Menu('账户信息',
#                                    '/APKManager/edit_cpinfo.pp',
#                                    "/APKManager/personal_center/edit.pp"))
#         personal.add_sub_menu(Menu('站内信',
#                                    '/APKManager/edit_cpinfo.pp',
#                                    "/APKManager/personal_center/edit.pp"))
#         menu_list.append(personal.to_dict())
#
#     game = Menu("游戏管理", '', "/APKManager/game_center/edit.pp")
#     if priv & Priv.kUploadGame:
#         game.add_sub_menu(Menu('上传游戏',
#                                '/APKManager/edit_game.pp',
#                                "/APKManager/game_center/edit.pp"))
#         game.add_sub_menu(Menu('在线游戏',
#                                '/APKManager/query_game.pp?status=3',
#                                "/APKManager/game_center/query.pp?status=3"))
#         game.add_sub_menu(Menu('待处理游戏',
#                                '/APKManager/query_game.pp',
#                                "/APKManager/game_center/query.pp?status=255"))
#         menu_list.append(game.to_dict())
#
#     if priv & Priv.kVerifyCP:
#         menu_list.append(Menu('资质审核',
#                               '/APKManager/show_cp_list.pp',
#                               "/APKManager/auditing_center/query_cp.pp?status=3").to_dict())
#
#     audit_mgmt = Menu('审核管理', '', "/APKManager/auditing_center/query_game.pp?level=1&status=2")
#     if priv & Priv.kFirstTrial:
#         audit_mgmt.add_sub_menu(Menu('初审待审核',
#                                      '/APKManager/show_game_list.pp?level=1&status=2',
#                                      "/APKManager/auditing_center/query_game.pp?level=1&status=2"))
#
#         audit_mgmt.add_sub_menu(Menu('初审打回列表', '/APKManager/show_game_list.pp?level=1&status=-1',
#                                      "/APKManager/auditing_center/query_game.pp?level=1&status=-1"))
#
#         audit_mgmt.add_sub_menu(Menu('初审通过列表', '/APKManager/show_game_list.pp?level=1&status=3',
#                                      "/APKManager/auditing_center/query_game.pp?level=1&status=3"))
#
#     if priv & Priv.kReview:
#         audit_mgmt.add_sub_menu(Menu('复审待审核',
#                                      '/APKManager/show_game_list.pp?level=2&status=2',
#                                      "/APKManager/auditing_center/query_game.pp?level=2&status=2"))
#         audit_mgmt.add_sub_menu(Menu('复审打回列表',
#                                      '/APKManager/show_game_list.pp?level=2&status=-1',
#                                      "/APKManager/auditing_center/query_game.pp?level=2&status=-1"))
#         audit_mgmt.add_sub_menu(Menu('复审通过列表',
#                                      '/APKManager/show_game_list.pp?level=2&status=3',
#                                      "/APKManager/auditing_center/query_game.pp?level=2&status=3"))
#
#     if len(audit_mgmt.submenu): menu_list.append(audit_mgmt.to_dict())
#
#     item = 0
#     for m in menu_list:
#         m["url"] = "/APKManager/?item=%d" % (item)
#
#         subitem = 0
#         for subm in m["sub_menus"]:
#             subm["url"] = "/APKManager/?item=%d&subitem=%d" % (item, subitem)
#             subitem += 1
#         item += 1
#
#     return menu_list
#
#
# @login_required(login_url=LOGIN_URL)
# def entry(request, *args, **kwargs):
#     if request.method == "GET":
#         item = request.GET.get('item')
#         subitem = request.GET.get('subitem')
#         menu_list = get_menu_by_privileges(request.session.get('privileges', 0))
#         menu = None
#
#         try:
#             if item:
#                 request.session["item"] = int(item)
#                 menu = menu_list[int(item)]
#
#             if subitem:
#                 request.session["subitem"] = int(subitem)
#                 menu = menu["sub_menus"][int(subitem)]
#
#             if menu:
#                 return HttpResponseRedirect(menu['handler'])
#         except:
#             return HttpResponseBadRequest()
#     else:
#         return HttpResponseBadRequest()
#
#
# # Login pages.
# class Login(View):
#     def get(self, request):
#         logout_request(request)
#         if not request.session.has_key('validation_code'):
#             randcode = random_str(4,
#                                   '1234567890qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP')
#             request.session['validation_code'] = randcode
#         else:
#             randcode = request.session['validation_code']
#         valid_code = generate_code_image(randcode, webconf.TEMP_DIR)
#         return render(request, 'html/login.html', {"validation_code_img": valid_code})
#
#     # validate username and password
#     def post(self, request):
#         try:
#             form = LoginForm(request.POST)
#             if not form.is_valid(): raise APKError.InvalidArguments
#
#             if request.session['validation_code'].lower() != form.data['validation_code'].lower():
#                 raise APKError.InvalidCode
#
#             wbact = model_find(WbAccount, account=form.data['username'])
#             if not wbact:
#                 raise APKError.NoAccountFound
#
#             md5pwd = hashlib.md5()
#             md5pwd.update(request.POST.get('password'))
#             if md5pwd.hexdigest() != wbact.password:
#                 raise APKError.NoAccountFound
#
#             login_request(request, wbact.id)
#             privs = Priv.get_privilege(wbact)
#             request.session['privileges'] = privs
#             menu = get_menu_by_privileges(privs)
#             del request.session['validation_code']
#
#             if len(menu[0]['sub_menus']):
#                 url = menu[0]["sub_menus"][0]['url']
#             else:
#                 url = menu[0]['url']
#
#             return json_response(APKError.Ok, {"url": url})
#
#         except GBErr as e:
#             return json_response(e)
#
#
#     @staticmethod
#     def logout(request):
#         logout_request(request)
#         return HttpResponseRedirect("/APKManager/login/")
#
#
# class Test(View):
#     def get(self, request, *args, **kwargs):
#         # form = GameForm()
#         return render(request, 'html/test.html')
#
#     def post(self, request, type):
#         form = GameForm(request.POST, request.FILES)
#         if not form.is_valid():
#             print(str(form.errors))
#             pass
#         else:
#             print(str(form.cleaned_data))

from .models import *
from .errcode import *
from Common.string import *
from Common.utils import generate_code_image


def json_response(errcode, object=None):
    data = {"rltcode": errcode.errcode,
            "rltmsg": errcode.errmsg,
            "object": object}
    return JsonResponse(data)


menus = None
models = None


def config_menu(user):
    global menus
    if menus:
        return menus

    menus = []
    for g in user.groups.all():
        if g.name.lower() == "supplier":
            menu = Menu("个人中心")
            menu.add_sub_menu(Menu("上传资质", handler="upload_supplier_info.pp").to_dict())
            menu.add_sub_menu(Menu("站内信").to_dict())
            menus.append(menu.to_dict())

            menu = Menu("游戏管理")
            menu.add_sub_menu(Menu("上传游戏", handler="upload_game.pp").to_dict())
            menu.add_sub_menu(Menu("已上线游戏", handler="query_game_list.pp?online=1").to_dict())
            menu.add_sub_menu(Menu("待处理游戏", handler="query_game_list.pp?online=0").to_dict())
            menus.append(menu.to_dict())
        elif g.name.lower() == "senior auditor":
            menu = Menu("资质审核", handler="query_supplier_list.pp?")
            menus.append(menu.to_dict())
            menu = Menu("初审管理")
            menu.add_sub_menu(Menu("初审待审核", handler="query_game_list.pp?level=1&status=2").to_dict())
            menu.add_sub_menu(Menu("初审通过列表", handler="query_game_list.pp?level=1&status=3").to_dict())
            menu.add_sub_menu(Menu("初审打回列表", handler="query_game_list.pp?level=1&status=-1").to_dict())
            menus.append(menu.to_dict())
        elif g.name.lower() == "junior auditor":
            menu = Menu("复审管理")
            menu.add_sub_menu(Menu("复审待审核", handler="query_game_list.pp?level=2&status=2").to_dict())
            menu.add_sub_menu(Menu("复审通过列表", handler="query_game_list.pp?level=2&status=3").to_dict())
            menu.add_sub_menu(Menu("复审打回列表", handler="query_game_list.pp?level=2&status=-1").to_dict())
            menus.append(menu.to_dict())

    for m in menus:
        m.url = "/APKManager/entry/?menu=%d" % (menus.index(m))
        for sub in m.sub_menus:
            sub.url = "/APKManager/entry/?menu=%d&item=%d" % (menus.index(m),
                                                              m.sub_menus.index(sub))

    return menus


def config_render(method):
    def wrapped(request, *args, **kwargs):
        render_args = {
            'urls': {
                "login": "/APKManager/login/",
                "logout": "/APKManager/logout/",
                "change_password": "/APKManager/change_password/",
                "upload_supplier_info": "/APKManager/upload_supplier_info.pp",

            },
        }

        menu_list = config_menu(request.user)
        menu = request.session.get('menu', 0)
        item = request.session.get('item', 0)

        for m in menu_list:
            if int(menu) == menu_list.index(m):
                m['active'] = True
                for sub in m["sub_menus"]:
                    if int(item) == m["sub_menus"].index(sub):
                        sub["active"] = True
                    else:
                        sub["active"] = False
            else:
                m["active"] = False
        render_args['menu_list'] = menu_list
        setattr(request, "render_args", render_args)
        return method(request, *args, **kwargs)

    return wrapped


def permissions_required(**kwargs):
    perms = kwargs.get('permissions')
    redirect_url = kwargs.get('redirect_url')

    def check_perms(proc):
        @login_required(login_url="")
        def wraped(request, *args, **kwargs2):
            for p in perms:
                if request.user.has_perm(p):
                    return proc(request, *args, **kwargs2)

            if not redirect_url:
                return HttpResponseRedirect(redirect_url)
            else:
                return json_response(errPermissionDenied)

        return wraped

    return check_perms


@login_required(login_url='')
@config_render
def entry(request, *args, **kwargs):
    menu = request.GET.get('menu')
    item = request.GET.get('item')
    redirect = request.GET.get('redirect')

    request.session['menu'] = menu
    request.session['item'] = item

    return HttpResponseRedirect(redirect)


@config_render
def logout(request, *args, **kwargs):
    logout(request)
    return HttpResponseRedirect()


@config_render
def login(request, *args, **kwargs):
    render_args = request.render_args

    if request.method == "GET":
        if request.user.is_authenticated():
            return HttpResponseRedirect()
        randcode = str_random(4, '1234567890qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP')
        request.session['validation_code'] = randcode
        code_img = generate_code_image(randcode)
        path = "%s/%s.png"%(webconf.TEMP_DIR, randcode)
        render_args['code_image_path'] = path
        code_img.save(path)
        return render(request, "html/login.html", render_args)
    elif request.method == "POST":
        try:
            code, username, password = get_request_parameters(request.POST,
                                                              'validation_code',
                                                              'username',
                                                              'password')
            if not request.session.has_key('validation_code'):
                raise errInvalidRequest

            if code != request.session['validation_code']:
                raise errInvalidValidationCode

            user = authenticate(username=username, password=password)
            if not user:
                raise errUserNotFound
            if user.is_active:
                login(request, user)
            return json_response(errOK, {"redirect_url": "/APKManager/?"})

        except GBErr as e:
            return json_response(e)


@login_required(login_url='')
@permissions_required(permissions=["add_wbsupplier"])
@config_render
def upload_supplier_info(request, *args, **kwargs):
    render_args = request.render_args
    if request.method == "GET":
        supplier_info = model_find(WbSupplier, user=request.session.user)
        render_args['supplier_info'] = supplier_info

        if not supplier_info or supplier_info.status.key == 'Rejected':
            return render(request, 'html/upload_supplier.html', render_args)
        elif supplier_info.status.key in ('Submitted', 'Auditing'):
            return render(request, 'html/supplier_submitted.html', render_args)
        elif supplier_info.status.key == "Done":
            return render(request, 'html/show_supplier.html', render_args)
        return HttpResponseBadRequest()
    elif request.method == "POST":
        try:
            supplier = Helper.save_supplier(request.session.user, **request.POST)
            model_set(supplier, status=WbAudit.SUBMITTED)
            return render(request, "html/suplier_submitted.html", render_args)
        except GBErr as e:
            render_args['error_message'] = e.errmsg
            return render(request, "html/error_page.html", render_args)


@login_required(login_url='')
@permissions_required(permissions=["add_wbsupplier", "change_wbsupplier_status"])
@config_render
def query_supplier_list(request, *args, **kwargs):
    pass
